package com.community.community.service;

import com.community.community.mapper.GoodMapper;
import com.community.community.pojo.Result;
import com.community.community.pojo.dto.GoodDto;
import com.community.community.pojo.entity.Good;
import com.community.community.pojo.vo.GoodVo;
import com.community.community.pojo.vo.UserVo;
import com.community.community.untils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class GoodService {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private GoodMapper goodMapper;

    public Result add(HttpServletRequest request, GoodDto goodDto) {
        Integer userId = jwtUtil.extractUserId(request);

        log.info("上传商品,{}",goodDto);
        Good good = new Good();
        good.setTitle(goodDto.getTitle());
        good.setDescription(goodDto.getDescription());
        good.setUserId(userId);
        if(goodDto.getType()== 1){
            //type=1为出租
             good.setRentDay(goodDto.getRentDay());
        }
        good.setType(goodDto.getType());
        good.setPrice(goodDto.getPrice());
        if(goodDto.getImages()!=null){
            good.setImages(String.join(",", goodDto.getImages()));
        }
        goodMapper.insert(good);

        return Result.success();
    }

    public Result<List<GoodVo>> commandList(Integer page) {
        List<GoodVo> list = goodMapper.commandList((page-1)*20);
        List<GoodVo> listvo = list.stream()
                .peek(item -> {
                    String images = item.getImages();
                    if (images != null && !images.isEmpty()) {
                        item.setImageUrls(Arrays.asList(item.getImages().split(",")));
                    }
                })
                .collect(Collectors.toList());
        return Result.success(listvo);
    }

    public Result<Good> detail(Integer id) {
        Good good = goodMapper.selectById(id);
        if(good.getImages()!=null && !good.getImages().isEmpty()){
            good.setImageUrls(Arrays.asList(good.getImages().split(",")));
        }
        return Result.success(good);
    }
}
